package cn.com.libertymutual.sp.service.impl;

import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import com.alibaba.fastjson.JSON;

import cn.com.libertymutual.core.base.dto.ResponseBaseDto;
import cn.com.libertymutual.core.redis.util.RedisUtils;
import cn.com.libertymutual.core.security.encoder.Md5PwdEncoder;
import cn.com.libertymutual.core.util.BeanUtilExt;
import cn.com.libertymutual.core.util.Constants;
import cn.com.libertymutual.core.util.DateUtil;
import cn.com.libertymutual.core.util.enums.CoreServiceEnum;
import cn.com.libertymutual.core.util.uuid.UUID;
import cn.com.libertymutual.core.web.ServiceResult;
import cn.com.libertymutual.core.web.util.RequestUtils;
import cn.com.libertymutual.sp.bean.TbSpApplicant;
import cn.com.libertymutual.sp.bean.TbSpOrder;
import cn.com.libertymutual.sp.bean.TbSpSaleLog;
import cn.com.libertymutual.sp.biz.ProductBiz;
import cn.com.libertymutual.sp.dao.ApplicantDao;
import cn.com.libertymutual.sp.dao.SpOrderDao;
import cn.com.libertymutual.sp.dao.SpSaleLogDao;
import cn.com.libertymutual.sp.dao.TbSysHotareaDao;
import cn.com.libertymutual.sp.dto.CommonQueryRequestDTO;
import cn.com.libertymutual.sp.dto.InsureQuery;
import cn.com.libertymutual.sp.dto.PlanDto;
import cn.com.libertymutual.sp.dto.axtx.AppliInsuredDto;
import cn.com.libertymutual.sp.dto.axtx.GuaranteeInfo;
import cn.com.libertymutual.sp.dto.axtx.ItemCarDto;
import cn.com.libertymutual.sp.dto.axtx.PolicyDataDto;
import cn.com.libertymutual.sp.dto.axtx.UnderwriteRequestDto;
import cn.com.libertymutual.sp.dto.queryplans.CrossSalePlan;
import cn.com.libertymutual.sp.dto.queryplans.QueryPlansResponseDTO;
import cn.com.libertymutual.sp.dto.savePlan.PropsalSaveRequestDto;
import cn.com.libertymutual.sp.service.api.AxtxService;
import cn.com.libertymutual.sp.service.api.BranchSetService;
import cn.com.libertymutual.sp.service.api.InsureService;
import cn.com.libertymutual.sp.service.api.ProductService;
import cn.com.libertymutual.sp.service.api.ShopService;
import cn.com.libertymutual.sp.service.api.UserService;
import cn.com.libertymutual.sys.bean.SysServiceInfo;
import cn.com.libertymutual.sys.service.api.ISequenceService;

@Service("AxtvService")
public class AxtvServiceImpl implements AxtxService {

	@Resource
	RestTemplate restTemplate; // 用他来访问http接口
	// @Resource HeadInfo headInfo;

	@Autowired
	private SpOrderDao spOrderDao;

	Md5PwdEncoder md5PwdEncoder = new Md5PwdEncoder();

	private Logger log = LoggerFactory.getLogger(getClass());
	@Resource
	private RedisUtils redisUtils;

	@Autowired
	private ShopService shopService;

	@Autowired
	private ApplicantDao applicantDao;

	@Autowired
	private ISequenceService iSequenceService;

	@Resource
	private ProductService productService;
	@Resource
	private BranchSetService branchSetService;// 机构

	@Autowired
	private SpSaleLogDao spSaleLogDao;

	@Autowired
	private TbSysHotareaDao tbSysHotareaDao;

	@Autowired
	private UserService userService;

	@Autowired
	private InsureService insureService;

	@Resource
	private ProductBiz productBiz;
	
	@Override
	public ServiceResult insure(PropsalSaveRequestDto request) {
		ServiceResult serviceResult = new ServiceResult();
		GuaranteeInfo guaranteeInfo = request.getAxtx();
		InsureQuery insureQuery = request.getInsureQuery();
		// request = productService.findRate(request,true);
		TbSpSaleLog saleLog = new TbSpSaleLog();
		// 设置佣金
		request = productService.findRate(request, true);

		saleLog.setOperation(TbSpSaleLog.OPERATION_INSURE);
		saleLog.setRequestTime(new Date());
		Object objData = new QueryPlansResponseDTO();
		objData = redisUtils
				.get(Constants.SALE_QUERY_PLAN_SAVE + insureQuery.getMinAge() + ":" + insureQuery.getDeadLine() + ":" + insureQuery.getPlanId());
		if (null == objData) {
			productService.queryPlan(insureQuery.getPlanId(), Integer.parseInt(insureQuery.getMinAge()), Integer.parseInt(insureQuery.getDeadLine()));
			objData = (QueryPlansResponseDTO) redisUtils
					.get(Constants.SALE_QUERY_PLAN_SAVE + insureQuery.getMinAge() + ":" + insureQuery.getDeadLine() + ":" + insureQuery.getPlanId());
		}
		
//		try {
//			objData = redisUtils
//					.get(Constants.SALE_QUERY_PLAN_SAVE + insureQuery.getMinAge() + ":" + insureQuery.getDeadLine() + ":" + insureQuery.getPlanId()+":"+guaranteeInfo.getSeatNum());
//			if (null == objData) {
//				productBiz.queryPlans(insureQuery.getPlanId(),insureQuery.getMinAge(), insureQuery.getDeadLine(),guaranteeInfo.getSeatNum());
//				objData = (QueryPlansResponseDTO) redisUtils
//						.get(Constants.SALE_QUERY_PLAN_SAVE + insureQuery.getMinAge() + ":" + insureQuery.getDeadLine() + ":" + insureQuery.getPlanId()+":"+guaranteeInfo.getSeatNum());
//			}		
//		}catch(Exception e) {
//			saleLog.setRequestData(BeanUtilExt.toJsonString(request));
//			saleLog.setResponseData("校验方案失败，请联系管理员");
//			spSaleLogDao.save(saleLog);
//			serviceResult.setFail();
//			serviceResult.setResult("校验方案失败，请联系管理员");
//			log.error(TbSpOrder.ERROR_03);
//			return serviceResult;
//		}	
		
		
		
		QueryPlansResponseDTO savePlans = (QueryPlansResponseDTO) objData;
		CrossSalePlan plan = savePlans.getPlanLists().get(0);

		UnderwriteRequestDto underWriteRequestDto = new UnderwriteRequestDto();
		PolicyDataDto policyDataDto = new PolicyDataDto();
		ItemCarDto itemCarDto = new ItemCarDto();
		AppliInsuredDto appliInsuredDto = new AppliInsuredDto();

		guaranteeInfo.setSumPremium(Double.parseDouble(plan.getPlanPrice()));
		appliInsuredDto.setInsuredName(guaranteeInfo.getName());
		appliInsuredDto.setIdentifyNumber(guaranteeInfo.getIdNum());
		appliInsuredDto.setLinkMobile(guaranteeInfo.getPhoneNum());
		appliInsuredDto.setEmail(guaranteeInfo.getMailAddress());
		// appliInsuredDto.setIdentifyType("01");
		appliInsuredDto.setIdentifyType(guaranteeInfo.getIdentifyType());
		appliInsuredDto.setLinkTel(guaranteeInfo.getPhoneNum());
		appliInsuredDto.setLinkName(guaranteeInfo.getName());
		appliInsuredDto.setInsuredType("1");

		itemCarDto.setLicenseNo(guaranteeInfo.getCarLicenseNum());
		itemCarDto.setFrameNo(guaranteeInfo.getCarFrameNum());
		itemCarDto.setCarType("1");
		itemCarDto.setNature("1");
		itemCarDto.setBrandName("1");

		Map map = (Map) redisUtils.get(Constants.SYS_SERVICE_INFO);

		if ("5".equals(guaranteeInfo.getSeatNum())) {
			itemCarDto.setItemCarSeatCount(5);
			itemCarDto.setItemCarSeatCountInsured(5);
		} else {
			itemCarDto.setItemCarSeatCount(7);
			itemCarDto.setItemCarSeatCountInsured(7);
		}
		Date time = new Date();
		policyDataDto.setStartDate(guaranteeInfo.getStringDate());
		policyDataDto.setInputDate(DateUtil.dateFromat(time.getTime()));
		policyDataDto.setPremium(guaranteeInfo.getSumPremium());
		policyDataDto.setAgreementCode(guaranteeInfo.getAgreementCode());
		if (!("undefined").equalsIgnoreCase(guaranteeInfo.getSaleCode())) {
			policyDataDto.setSaleCode(guaranteeInfo.getSaleCode());
			policyDataDto.setSalerName(guaranteeInfo.getSalerName()); // 销售人员名称 20171113 bob.kuang
		} else {
			policyDataDto.setSaleCode("");
		}
		policyDataDto.setProductCode(guaranteeInfo.getPlanCode());
		policyDataDto.setRiskCode("2724");

		underWriteRequestDto.setItemCarDto(itemCarDto);
		underWriteRequestDto.setAppliInsuredDto(appliInsuredDto);

		String senUserCode = "";
		String curUserCode = userService.getTopUserCode(request.getUser().getUserCode());
		if (StringUtils.isNotBlank(insureQuery.getRefereeId())) {
			senUserCode = insureQuery.getRefereeId();
		} else {
			senUserCode = curUserCode;
		}

		TbSpOrder order = new TbSpOrder();
		try {

			order = insureService.setAgrInfo(order, policyDataDto.getAgreementCode(), senUserCode);

			if (StringUtils.isNotBlank(policyDataDto.getSaleCode()) && StringUtils.isBlank(policyDataDto.getSalerName())) {
				policyDataDto.setSalerName(insureService.getSaleCode(policyDataDto.getAgreementCode(), policyDataDto.getSaleCode()));

			}

		} catch (Exception e) {
			saleLog.setMark("查询业务关系代码对应信息出错");
			spSaleLogDao.save(saleLog);
			log.error(e.toString());
		}

		policyDataDto.setComm1Rate(request.getComm1Rate());
		underWriteRequestDto.setPolicyDataDto(policyDataDto);

		SysServiceInfo callServiceInfo = (SysServiceInfo) map.get(CoreServiceEnum.CALLBACK_URL.getUrlKey());
		underWriteRequestDto.getPolicyDataDto().setCallBackUrl(callServiceInfo.getUrl());
		// headInfo.setHeadInfo(underWriteRequestDto);
		long beginTime;
		long endTime;
		long curDate = new Date().getTime();
		try {
			beginTime = DateUtil.convertStringToDate(guaranteeInfo.getStringDate()).getTime();
			endTime = DateUtil.convertStringToDate(guaranteeInfo.getEndTime()).getTime();
		} catch (Exception e) {
			serviceResult.setFail();
			serviceResult.setResult("投保失败,01，请稍后再试！");
			log.error(TbSpOrder.ERROR_01);
			saleLog.setMark(TbSpOrder.ERROR_01);
			saleLog.setRequestData(BeanUtilExt.toJsonString(request));
			spSaleLogDao.save(saleLog);
			return serviceResult;
		}
		// 日期信息不符合投保规则
		if (beginTime < curDate || endTime < beginTime || curDate > endTime) {
			serviceResult.setFail();
			log.error(TbSpOrder.ERROR_01);
			saleLog.setMark(TbSpOrder.ERROR_01);
			saleLog.setRequestData(BeanUtilExt.toJsonString(request));
			spSaleLogDao.save(saleLog);
			serviceResult.setResult("投保失败,01,请稍后再试！");
			return serviceResult;
		}

		// log.info( submitUnderwriteURL);
		// log.info("{}", underWriteRequestDto);

		// String test = BeanUtilExt.toJsonString(requestEntity);
		// saleLog.setRequestData(BeanUtilExt.toJsonString(requestEntity) + "
		// URL:"+request.getAccessUrl());
		// saleLog.setRequestData(requestEntity.toString());
		LinkedHashMap<String, Object> saveMap = new LinkedHashMap<String, Object>();
		SysServiceInfo sysServiceInfo = (SysServiceInfo) map.get(CoreServiceEnum.AXTX_2724_INSURE.getUrlKey());
		HttpHeaders headers = RequestUtils.genEncryptHttpHeaders(sysServiceInfo.getUserName(), sysServiceInfo.getPassword());
		underWriteRequestDto.setPartnerAccountCode(sysServiceInfo.getUserName());
		String BussFormNo = insureQuery.getRisk() + DateUtil.getStringDateYyMMdd() + UUID.getShortUuid();
		underWriteRequestDto.setFlowId(BussFormNo);

		underWriteRequestDto.setOperatorDate(DateUtil.getStringDate());
		underWriteRequestDto.setRecordCode(sysServiceInfo.getTocken());
		underWriteRequestDto.setAgreementNo(sysServiceInfo.getTocken());
		if (StringUtils.isNotBlank(insureQuery.getSingleMember())) {
			underWriteRequestDto.getPolicyDataDto().setTrdSalesCode(insureQuery.getSingleMember());
		}

		HttpEntity<UnderwriteRequestDto> requestEntity = new HttpEntity<UnderwriteRequestDto>(underWriteRequestDto, headers);
		saleLog.setRequestData(BeanUtilExt.toJsonString(requestEntity) + "  URL:" + insureQuery.getAccessUrl() + "<br>log:" + request.getLog());
		try {
			serviceResult = restTemplate.postForObject(sysServiceInfo.getUrl(), requestEntity, ServiceResult.class);
			saleLog.setResponseData(BeanUtilExt.toJsonString(serviceResult));
			// saleLog.setResponseData(serviceResult.toString());
			saveMap = (LinkedHashMap<String, Object>) serviceResult.getResult();
		} catch (RestClientException e) {

			saleLog.setMark(TbSpOrder.ERROR_03);
			spSaleLogDao.save(saleLog);
			serviceResult.setFail();
			serviceResult.setResult("投保失败,03,请稍后再试！");
			log.error(TbSpOrder.ERROR_03);
			return serviceResult;
			// serviceResult.setFail();
			// serviceResult.setResult("投保失败");
			// log.error("cn.com.libertymutual.mobile.insure.service.impl.IndexServiceImpl[ERROR]",
			// e);
		}

		String flowId = iSequenceService.getOrderSequence(insureQuery.getRisk());
		Boolean state = (Boolean) saveMap.get("status");
		String proposalNo = "";

		if (!state) {
			serviceResult.setResult(saveMap.get("resultMessage"));
			saleLog.setMark(TbSpOrder.ERROR_05);
			spSaleLogDao.save(saleLog);
			log.error(TbSpOrder.ERROR_05 + saveMap.get("resultMessage"));
			// 05:返回信息不存在responseJson
			serviceResult.setFail();
			return serviceResult;
		} else {
			LinkedHashMap<String, Object> reqData = new LinkedHashMap<String, Object>();
			reqData = (LinkedHashMap<String, Object>) saveMap.get("proposalSaveResponseDto");
			try {
				proposalNo = reqData.get("bussNewNo").toString();
			} catch (Exception e) {
				// serviceResult.setResult(reqData.get("responseHeadDto"));
				saleLog.setMark(TbSpOrder.ERROR_05);
				spSaleLogDao.save(saleLog);
				log.error(TbSpOrder.ERROR_05 + saveMap.get("responseHeadDto"));
				// 05:返回信息不存在responseJson
				serviceResult.setFail();
				return serviceResult;
			}
			// JSONObject jsonObject =
			// JSON.parseObject(saveMap.get("proposalSaveResponseDto").toString());
			// proposalNo=jsonObject.getString("bussNewNo");
		}

		try {
			TbSpApplicant appliSpal = new TbSpApplicant();
			appliSpal.setOrderNo(flowId);
			appliSpal.setCarId(guaranteeInfo.getIdNum());
			appliSpal.setCarType("01");
			appliSpal.setEmail(guaranteeInfo.getMailAddress());
			appliSpal.setMobile(guaranteeInfo.getPhoneNum());
			appliSpal.setName(guaranteeInfo.getName());
			appliSpal.setNatureType("1");
			appliSpal.setOccupation("");
			// appliSpal.setRelation("01");
			appliSpal.setSex(guaranteeInfo.getSex());
			appliSpal.setBirth(DateUtil.convertStringToDate(guaranteeInfo.getBirth()));
			appliSpal.setType(TbSpApplicant.TYPE_POLICY);
			appliSpal.setFrameNum(guaranteeInfo.getCarFrameNum());
			appliSpal.setPlateNum(guaranteeInfo.getCarLicenseNum());
			applicantDao.save(appliSpal);

			TbSpApplicant insuredSpal = new TbSpApplicant();
			insuredSpal.setOrderNo(flowId);
			insuredSpal.setCarId(guaranteeInfo.getIdNum());
			insuredSpal.setCarType("01");
			insuredSpal.setEmail(guaranteeInfo.getMailAddress());
			insuredSpal.setMobile(guaranteeInfo.getPhoneNum());
			insuredSpal.setName(guaranteeInfo.getName());
			insuredSpal.setNatureType("1");
			insuredSpal.setOccupation("");
			insuredSpal.setRelation("01");
			insuredSpal.setSex(guaranteeInfo.getSex());
			insuredSpal.setBirth(DateUtil.convertStringToDate(guaranteeInfo.getBirth()));
			insuredSpal.setType(TbSpApplicant.TYPE_INSURED);
			insuredSpal.setFrameNum(guaranteeInfo.getCarFrameNum());
			insuredSpal.setPlateNum(guaranteeInfo.getCarLicenseNum());
			applicantDao.save(insuredSpal);
		} catch (Exception e) {
			serviceResult.setFail();
			saleLog.setMark(TbSpOrder.ERROR_06);
			spSaleLogDao.save(saleLog);
			log.error(TbSpOrder.ERROR_06);
			serviceResult.setResult("投保失败,06,请稍后再试！");
			// 06:信息表回写失败

			log.error(e.toString());
			// TODO Auto-generated catch block
			// e.printStackTrace();
			return serviceResult;
		}

		try {
			// order.setAccessUrl(request.getAccessUrl());
			order.setOrderNo(flowId);
			order.setAmount(Double.parseDouble(plan.getPlanPrice())); // 总金额
			order = insureService.setOrderInitData(order, insureQuery);

			order.setUserId(curUserCode);
			order.setIdNo(guaranteeInfo.getIdNum()); // 证件号码
			order.setStartDate(DateUtil.convertStringToDate(guaranteeInfo.getStringDate())); // 起保日期
			order.setEndDate(DateUtil.convertStringToDate(guaranteeInfo.getEndTime())); // 保险止限额
			order.setOrderDetail(JSON.toJSONString(request.getKinds())); // 订单详情
			order.setProposalNo(proposalNo);
			order.setFrameNum(guaranteeInfo.getCarFrameNum());
			order.setPlateNum(guaranteeInfo.getCarLicenseNum());
			order.setRefereeId(userService.getTopUserCode(insureQuery.getRefereeId())); // 推荐人
			order = insureService.setInsureBrachCode(order, insureQuery, request);
			order.setAgreementNo(guaranteeInfo.getAgreementCode()); // 业务关系代码
			order.setApplicantName(guaranteeInfo.getName()); // 投保人名字
			order.setCommissionRate(request.getComm1Rate());
			order.setBranchOffice(guaranteeInfo.getChannelName());
			order.setPlanId(String.valueOf(plan.getPlanId()));
			order.setAgreementNo(underWriteRequestDto.getPolicyDataDto().getAgreementCode());
			spOrderDao.save(order);
			serviceResult.setSuccess();

			// TbSpOrder order = new TbSpOrder();
			// order.setStatus("2"); // 订单状态
			// order.setAmount(request.getAmount()); // 总金额
			// order.setRiskName(request.getRiskName()); // 险种名字
			// order.setRiskCode(request.getRisk()); // 险种CODE
			// order.setIdNo(guaranteeInfo.getIdNum()); // 证件号码
			// order.setClauseUrl(request.getClauseUrl()); // 条款url
			// order.setPlanCode(request.getPlanId()); // 获得计划代码
			// order.setPlanName(request.getPlanName()); // 获得计划名称
			// order.setCreateTime(new Date()); // 订单创建时间
			// order.setUpdateTime(new Date()); // 更细那时间
			// order.setPolicyNo(proposalNo);
			// order.setRemark(""); // 备注
			// order.setOrderDetail(JSON.toJSONString(request.getKinds())); // 订单详情
			// order.setProductId(request.getProductId()); // 产品id
			// order.setProductName(request.getProductName()); // 产品名称
			// order.setHouseAddress(""); // 房屋地址
			// order.setPayWay("7"); // 支付方式
			// order.setPaymentNo(""); // 支付流水号
			// // order.setProposalNo(riDto.getBussNewNo());
			//// order.setPolicyNo("");// 投保单号
			// order.setPayDate(null); // 支付日期，回掉的时候设置
			// order.setRefereeId(request.getRefereeId()); // 推荐人
			// order.setBranchCode(""); // 分公司
			// order.setTravelDestination("");
			// order.setAgreementNo(guaranteeInfo.getAgreementCode()); // 业务关系代码
			// order.setApplicantName(guaranteeInfo.getName()); // 投保人名字
			// order.setSaleType(""); // 销售渠道
			// order.setAddress("");
			// order.setBranchOffice(guaranteeInfo.getChannelName());
			// order.setStartDate(DateUtil.convertStringToDate(guaranteeInfo.getStringDate()));
			// // 起保日期
			// order.setEndDate(DateUtil.convertStringToDate(guaranteeInfo.getEndTime()));
			// // 保险止限额
			// spOrderDao.save(order);
		} catch (Exception e) {
			serviceResult.setFail();
			serviceResult.setResult("投保失败,07,请稍后再试！");
			saleLog.setMark(TbSpOrder.ERROR_07);
			spSaleLogDao.save(saleLog);
			log.error(TbSpOrder.ERROR_07);
		}
		spSaleLogDao.save(saleLog);
		return serviceResult;
	}

	@Override
	public ServiceResult findVin(CommonQueryRequestDTO querydto) {
		ServiceResult sr = new ServiceResult();
		Map map = (Map) redisUtils.get(Constants.SYS_SERVICE_INFO);
		SysServiceInfo sysServiceInfo = (SysServiceInfo) map.get(CoreServiceEnum.FIND_VIN.getUrlKey());
		querydto.setPartnerAccountCode(sysServiceInfo.getUserName());
		querydto.setFlowId(sysServiceInfo.getUserName() + DateUtil.dateFromat(new Date(), DateUtil.DATE_TIME_PATTERN3) + new Date().getTime());
		HttpHeaders headers = RequestUtils.genEncryptHttpHeaders(sysServiceInfo.getUserName(), sysServiceInfo.getPassword());
		HttpEntity<CommonQueryRequestDTO> requestEntity = new HttpEntity<CommonQueryRequestDTO>(querydto, headers);
		ResponseBaseDto res = new ResponseBaseDto();
		try {
			res = restTemplate.postForObject(sysServiceInfo.getUrl(), requestEntity, ResponseBaseDto.class);
		} catch (Exception e) {
			log.info(e.toString());
			sr.setFail();
			return sr;
		}
		if (res.getStatus() != null && res.getStatus()) {
			sr.setSuccess();
			sr.setResult(res.getResultMessage());
		} else {
			sr.setFail();
		}
		return sr;
	}

}
